import request from '@/utils/request'

// 获取秒杀活动列表
export function getSeckillList(params) {
  return request({
    url: '/seckill/seckill/activity/list',
    method: 'get',
    params
  }).catch(error => {
    console.error('获取秒杀活动列表失败，使用模拟数据:', error)
    // 如果API调用失败，返回模拟数据
    return getMockSeckillList(params)
  })
}

// 获取我的秒杀活动
export function getMySeckills(params) {
  return request({
    url: '/seckill/my-seckills',
    method: 'get',
    params
  }).catch(error => {
    console.error('获取我的秒杀失败，使用模拟数据:', error)
    return {
      code: 200,
      message: '获取成功',
      data: []
    }
  })
}

// 获取秒杀活动详情
export function getSeckillDetail(id) {
  return request({
    url: `/seckill/seckill/activity/detail/${id}`,
    method: 'get'
  }).catch(error => {
    console.error('获取秒杀活动详情失败，使用模拟数据:', error)
    return getMockSeckillDetail(id)
  })
}

// 获取秒杀商品列表（已合并到getSeckillDetail中）
export function getSeckillProducts(seckillId) {
  // 由于商品列表已包含在活动详情中，这里直接调用详情接口
  return getSeckillDetail(seckillId).then(response => {
    // 从活动详情中提取商品列表
    return {
      code: response.code,
      message: response.message,
      data: response.data?.products || []
    }
  })
}

// 获取秒杀商品详情
export function getSeckillProductDetail(productId) {
  return request({
    url: `/seckill/seckill/product/${productId}`,
    method: 'get'
  }).catch(error => {
    console.error('获取秒杀商品详情失败，使用模拟数据:', error)
    return getMockSeckillProductDetail(productId)
  })
}

// 创建秒杀活动
export function createSeckill(data) {
  return request({
    url: '/seckill/create',
    method: 'post',
    data
  })
}

// 更新秒杀活动
export function updateSeckill(data) {
  return request({
    url: '/seckill/update',
    method: 'put',
    data
  })
}

// 删除秒杀活动
export function deleteSeckill(id) {
  return request({
    url: `/seckill/delete/${id}`,
    method: 'delete'
  })
}


// 添加秒杀商品
export function addSeckillProduct(data) {
  return request({
    url: '/seckill/product/add',
    method: 'post',
    data
  })
}



// 参与秒杀
export function joinSeckill(data) {
  return request({
    url: '/seckill/join',
    method: 'post',
    data
  })
}

// 设置秒杀提醒
export function setSeckillReminder(data) {
  return request({
    url: '/seckill/reminder',
    method: 'post',
    data
  })
}

// 创建秒杀订单
export function createSeckillOrder(data) {
  return request({
    url: '/seckill/seckill/do',
    method: 'post',
    data
  }).catch(error => {
    console.error('创建秒杀订单失败，使用模拟数据:', error)
    return getMockSeckillOrderResponse(data)
  })
}

// 模拟秒杀订单响应
function getMockSeckillOrderResponse(data) {
  return Promise.resolve({
    code: 200,
    message: '秒杀订单创建成功',
    data: {
      orderId: Date.now(),
      status: 'pending',
      createTime: new Date().toISOString()
    }
  })
}

// ==================== 模拟数据（备用） ====================

// 模拟数据
const mockSeckillDetail = {
  id: 1,
  title: 'iPhone 15 Pro 限时秒杀',
  description: 'iPhone 15 Pro 系列限时秒杀，数量有限，先到先得！',
  image: '/static/images/seckill/iphone-banner.jpg',
  bannerImage: '/static/images/seckill/iphone-banner.jpg',
  status: 'ongoing',
  startTime: '2024-07-29 10:00:00',
  endTime: '2024-07-30 10:00:00',
  rules: '1. 每人限购1台\n2. 秒杀商品不支持退换货\n3. 请在30分钟内完成支付\n4. 活动最终解释权归本店所有',
  products: mockSeckillProducts
}

// 即将开始的活动
const mockUpcomingSeckill = {
  id: 2,
  title: '年货节大促销',
  description: '年货节期间，全场商品低至5折，快来抢购！',
  image: '/static/images/seckill/newyear-banner.jpg',
  bannerImage: '/static/images/seckill/newyear-banner.jpg',
  status: 'upcoming',
  startTime: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(), // 2小时后开始
  endTime: new Date(Date.now() + 26 * 60 * 60 * 1000).toISOString(), // 26小时后结束
  rules: '1. 全场商品5折起\n2. 每人限购3件\n3. 活动期间不支持退换货',
  products: mockSeckillProducts
}

// 已结束的活动
const mockEndedSeckill = {
  id: 3,
  title: '数码产品专场',
  description: '数码产品专场秒杀，手机、电脑、配件应有尽有！',
  image: '/static/images/seckill/digital-banner.jpg',
  bannerImage: '/static/images/seckill/digital-banner.jpg',
  status: 'ended',
  startTime: '2024-07-20 10:00:00',
  endTime: '2024-07-25 10:00:00',
  rules: '1. 数码产品专场\n2. 限时特价\n3. 数量有限',
  products: mockSeckillProducts
}

// 模拟秒杀商品详情数据（根据后台返回的数据结构）
const mockSeckillProductDetail = {
  createBy: null,
  createTime: "2025-07-30 21:44:52",
  updateBy: null,
  updateTime: "2025-07-30 21:44:52",
  remark: null,
  id: 1,
  activityId: 1,
  productId: 1001,
  productName: "iPhone 15 Pro 256GB",
  productImage: "/images/iphone15pro.jpg",
  seckillPrice: 7999.00,
  originalPrice: 9999.00,
  stock: 100,
  sales: 25,
  limitPerUser: 1,
  status: 1,
  activityTitle: "双11大促活动",
  remainingStock: 75,
  soldOut: false,
  discountAmount: 2000.00,
  discountRate: 20.0000
}

const mockSeckillProducts = [
  {
    id: 101,
    name: 'iPhone 15 Pro 128GB',
    title: 'iPhone 15 Pro 128GB',
    image: '/static/images/products/iphone15pro.jpg',
    seckillPrice: 7999,
    currentPrice: 7999,
    originalPrice: 8999,
    stock: 50,
    soldCount: 30,
    tags: ['限时特价', '热销']
  },
  {
    id: 102,
    name: 'iPhone 15 Pro 256GB',
    title: 'iPhone 15 Pro 256GB',
    image: '/static/images/products/iphone15pro.jpg',
    seckillPrice: 8999,
    currentPrice: 8999,
    originalPrice: 9999,
    stock: 30,
    soldCount: 20,
    tags: ['限时特价']
  },
  {
    id: 103,
    name: 'iPhone 15 Pro Max 128GB',
    title: 'iPhone 15 Pro Max 128GB',
    image: '/static/images/products/iphone15promax.jpg',
    seckillPrice: 8999,
    currentPrice: 8999,
    originalPrice: 9999,
    stock: 20,
    soldCount: 15,
    tags: ['限时特价', '新品']
  }
]

// 获取模拟秒杀活动列表
function getMockSeckillList(params) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        message: '获取成功',
        rows: [
          {
            id: 1,
            title: 'iPhone 15 Pro 限时秒杀',
            description: 'iPhone 15 Pro 系列限时秒杀，数量有限，先到先得！',
            status: 'ongoing',
            startTime: '2024-07-29 10:00:00',
            endTime: '2024-07-30 10:00:00',
            products: mockSeckillProducts
          },
          {
            id: 2,
            title: '年货节大促销',
            description: '年货节期间，全场商品低至5折，快来抢购！',
            status: 'upcoming',
            startTime: '2024-08-01 00:00:00',
            endTime: '2024-08-07 23:59:59',
            products: []
          },
          {
            id: 3,
            title: '数码产品专场',
            description: '数码产品专场秒杀，手机、电脑、配件应有尽有！',
            status: 'ended',
            startTime: '2024-07-20 10:00:00',
            endTime: '2024-07-25 10:00:00',
            products: []
          }
        ]
      })
    }, 500)
  })
}

// 获取模拟秒杀活动详情
function getMockSeckillDetail(id) {
  return new Promise((resolve) => {
    setTimeout(() => {
      let activityData
      
      // 根据ID返回不同的活动数据
      switch (parseInt(id)) {
        case 1:
          activityData = mockSeckillDetail
          break
        case 2:
          activityData = mockUpcomingSeckill
          break
        case 3:
          activityData = mockEndedSeckill
          break
        default:
          activityData = mockSeckillDetail
      }
      
      resolve({
        code: 200,
        message: '获取成功',
        data: {
          ...activityData,
          id: parseInt(id)
        }
      })
    }, 500)
  })
}

// 获取模拟秒杀商品列表
function getMockSeckillProducts(seckillId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        message: '获取成功',
        data: mockSeckillProducts
      })
    }, 500)
  })
}

// 获取模拟秒杀商品详情
function getMockSeckillProductDetail(productId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 根据商品ID返回不同的商品详情
      const productMap = {
        101: {
          ...mockSeckillProductDetail,
          id: 101,
          productId: 101,
          productName: "iPhone 15 Pro 128GB",
          seckillPrice: 7999.00,
          originalPrice: 8999.00,
          stock: 50,
          sales: 30,
          remainingStock: 20,
          soldOut: false
        },
        102: {
          ...mockSeckillProductDetail,
          id: 102,
          productId: 102,
          productName: "iPhone 15 Pro 256GB",
          seckillPrice: 8999.00,
          originalPrice: 9999.00,
          stock: 30,
          sales: 20,
          remainingStock: 10,
          soldOut: false
        },
        103: {
          ...mockSeckillProductDetail,
          id: 103,
          productId: 103,
          productName: "iPhone 15 Pro Max 128GB",
          seckillPrice: 9999.00,
          originalPrice: 10999.00,
          stock: 20,
          sales: 15,
          remainingStock: 5,
          soldOut: false
        }
      }
      
      const productDetail = productMap[productId] || {
        ...mockSeckillProductDetail,
        id: parseInt(productId)
      }
      
      resolve({
        msg: '操作成功',
        code: 200,
        data: productDetail
      })
    }, 500)
  })
} 